let id = 0;
import { pushTarget, popTarget } from './dep'
class Watcher {
  // watch 有唯一标识
  constructor(vm, exprOrfn, cb = () => { }, opts = {}) {
    // exprOrfn 表达式  cb 回调
    this.vm = vm;
    this.exprOrfn = exprOrfn;
    if (typeof exprOrfn == 'function') {
      // getter 就是  Watcher 传入的第2个函数
      this.getter = exprOrfn;
    }
    this.cb = cb;
    this.opts = opts;
    this.id = id++;
    this.deps = [];
    this.depsId = new Set();
    this.get()
  }
  get() {
    // 渲染watch  Dep.target = watcher;
    // msg 变化了 需要重新执行watch
    pushTarget(this)
    // 让当前传入的函数执行
    this.getter();
    popTarget
  }
  update() {
    this.get()
  }
  addDep(dep) {
    let id = dep.id;
    if (!this.depsId.has(id)) {
      this.depsId.add(id)
      this.deps.push(dep)
      dep.addSub(this)
    }
  }
}
export default Watcher;
